<?php
/**
 * 支付base类方法
 * 进行支付之前数据验证等。
 * @author ran.ran
 * @property 2016-4-17
 */
namespace components;

use yii\base\Action;
use services\models\Payment;
use yii\base\ErrorException;
use Yii;
use yii\base\Exception;
use services\models\OrderInfo;
use services\models\PayLog;

class BasePayMentAction extends Action
{
    /**
     * 订单id
     * @var int
     */
    public $orderId;
    
    /**
     * 验证订单密钥值
     * @var string
     */
    public $hashValue;
    
    /**
     * 交易记录信息
     * @var object
     */
    public $payment=false;
    
    /**
     * 认证密钥key
     * @var string
     */
    private $hashkey = '';
    
    /**
     * 订单名称
     * @var string
     */
    public $subject = '有试吗订单';
    
    /**
     * 订单描述
     * @var string
     */
    public $body = '有试吗订单';
    
    /**
     * 商品展示地址
     * @var string
     */
    public $showUrl = 'http://www.liketry.com/';
    
    /**
     * 异步通知
     * @var string
     */
    public $notifyUrl = null;
    
    /**
     * 页面通知
     * @var string
     */
    public $returnUrl = null;
    
    /**
     * 当前支付模式
     * @var string alipay|ccb|wxpay
     */
    public $mode = 'alipay';
    
    /**
     * 支付方式
     * @var string
     */
    public $pay_method = '';
    
    public function init(){
        
        //初始化获取订单order_info_id
        $this->orderId = Yii::$app->request->get('order_info_id', '');
        //验证密钥
        $this->hashValue = Yii::$app->request->get('hashValue', '');
        //支付方式
        $this->pay_method = Yii::$app->request->get('pay_method', 0);//支付方式
        //密钥字符串
        $this->hashkey = Yii::$app->params['hashkey'];
        
        //异步通知为空，获取默认异步通知，ccb建设银行、支付宝设置为固定的回调地址，不可更改，
        if(!$this->notifyUrl) {
           $this->notifyUrl  = Yii::$app->params[$this->mode]['notify_url'];
        }
        //页面通知为空，获取默认通知，微信没有页面通知，ccb建设银行、支付宝设置为固定的回调地址，不可更改，
        if(!$this->returnUrl) {
            $this->returnUrl  = Yii::$app->params[$this->mode]['return_url'];
        }
        
    }
    
    /**
     *验证订单信息
     */
    public  function validateOrderInfo() {
        
        if(intval($this->orderId) < 1) {
            throw  new Exception('订单错误');
        }

        try{
            $payment = $this->getPayment();
            
        }catch(Exception $e){
            throw  new Exception($e->getMessage());
        }

        //验证签名
        if($this->hashkey !== false && !$payment->validateData($this->hashValue, $this->hashkey)) {
            throw  new Exception('签名错误');
        }
        
        //验证订单是否已经支付
        if($payment->pay_status == OrderInfo::$PAY_STATUS_SUCCESS) {
            return ['flag'=>false,'msg'=>'订单已支付'];
        }
        
        //验证订单状态
        if($payment->status != OrderInfo::$STATUS_ORDER_CREATED) {
            throw  new Exception('订单状态错误');
        }
        
        //验证订单是否需要支付
        if(0 >= $payment->order_amount) {
           return ['flag'=>false,'msg'=>'订单无需支付'];
        }
        
        if(!empty($this->pay_method)) {
            //更改订单支付方式【支付宝、微信】
            if(is_numeric($this->pay_method) && in_array($this->pay_method, [OrderInfo::$PAY_TYPE_ALIPAY,OrderInfo::$PAY_TYPE_WEIXIN]))
            {
                $payment->pay_id = $this->pay_method;
                $payment->pay_name = OrderInfo::$PAY_TYPE_DESC[$this->pay_method];
                $payment->bank = OrderInfo::$PAY_TYPE_DESC[$this->pay_method];
            }else {
                //网银
                $payment->pay_id = OrderInfo::$PAY_TYPE_BANK_INTERNET;
                $payment->pay_name = $this->pay_method;
                $payment->bank = $this->pay_method;
            }
            
            if($payment->save()) {
                //插入支付日志
                $pay_log_info = PayLog::findOne(['order_info_id'=>$payment->order_info_id]);
                if(empty($pay_log_info)) {
    
                    $model = new PayLog();
                    $model->bestry_uid = $payment->bestry_uid;
                    $model->total_fee =  $payment->order_amount;
                    $model->order_info_id = $payment->order_info_id;
                    $model->order_sn = $payment->order_sn;
                    $model->pay_id = $payment->pay_id;
                    $model->pay_name = $payment->pay_name;
                    $model->bank  = $payment->bank;
                    $model->create_time = date("Y-m-d H:i:s");
                    $model->return_amount = $payment->reduce_amount;
                    $model->save();
                }
    
            }
        }
        
        return ['flag'=>true,'data'=>$payment];
    }
    
    
    /**
     * 通过order_info_id获取订单信息
     * @param int $id
     * @throws ErrorException
     */
    private function getPayment() {
        if($this->payment === false || $this->payment->order_info_id != $this->orderId) {

            try {
                $this->payment = Payment::getOrderInfoByPramas(['order_info_id' => $this->orderId]);
            } catch (Exception $e) {
                throw new Exception($e->getMessage());
            }
            if(!$this->payment) {
                throw new Exception('No record of the transaction');
            }
        }
    
        return $this->payment;
    }
    
}

?>